package com.oba.base.util;

import java.util.List;
import java.util.Stack;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;

import com.oba.base.interfaces.ITreeItem;
import com.oba.base.service.TreeUserObj;

public class TreeUtil {

	public static DefaultTreeModel createTree(List<? extends ITreeItem> orderItemList) {
		DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
		TreeUserObj<ITreeItem> obj = new TreeUserObj<ITreeItem>(rootNode);
		obj.setBo(orderItemList.get(0));
		obj.setExpanded(false);
		rootNode.setAllowsChildren(true);
		rootNode.setUserObject(obj);
		orderItemList.get(0).setNode(rootNode);
		DefaultTreeModel tree = new DefaultTreeModel(rootNode);
		Stack<DefaultMutableTreeNode> stack = new Stack<DefaultMutableTreeNode>();
		stack.push(rootNode);
		for (int i = 1; i < orderItemList.size(); i++) {
			DefaultMutableTreeNode addNode = new DefaultMutableTreeNode();
			TreeUserObj<ITreeItem> addObj = new TreeUserObj<ITreeItem>(addNode);
			addObj.setBo(orderItemList.get(i));
			addObj.setExpanded(false);
			addNode.setAllowsChildren(true);
			addNode.setUserObject(addObj);
			orderItemList.get(i).setNode(addNode);
			while (!stack.isEmpty()) {
				DefaultMutableTreeNode topNode = stack.peek();
				TreeUserObj<ITreeItem> addU = (TreeUserObj<ITreeItem>) addNode.getUserObject();
				TreeUserObj<ITreeItem> topU = (TreeUserObj<ITreeItem>) topNode.getUserObject();

				if (addU.getBo().isParent(topU.getBo())) {
					topNode.add(addNode);
					break;
				} else {
					stack.pop();
				}
			}
			if (stack.size() == 0) {
				DefaultMutableTreeNode treeRoot = (DefaultMutableTreeNode) tree.getRoot();
				treeRoot.add(addNode);
			}
			stack.push(addNode);
		}
		return tree;
	}

	public static void addChrid(MutableTreeNode parent, ITreeItem newItem) {
		DefaultMutableTreeNode node = new DefaultMutableTreeNode();
		TreeUserObj<ITreeItem> obj = new TreeUserObj<ITreeItem>(node);
		obj.setBo(newItem);
		node.setAllowsChildren(true);
		node.setUserObject(obj);
		newItem.setNode(node);
		((DefaultMutableTreeNode) parent).add(node);
	}
	
	public static void delNode() {
		
	}

}
